<?php 
include_once("includes/global.php");

@include_once("config/remote_config.php");
@include_once("config/image_config.php");
include_once("config/watermark_config.php");



function uploadEncode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	if($operation == 'DECODE') {
		//如果是解密，则先从安全的URL中转换回来
		$string = str_replace(array('-','_'),array('+','/'),$string);
		$mod4 = strlen($string) % 4;
		if ($mod4) {
			$string .= substr('====', $mod4);
		}
	}
	// 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
	$ckey_length = 4;

	// 密匙
	$key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

	// 密匙a会参与加解密
	$keya = md5(substr($key, 0, 16));
	// 密匙b会用来做数据完整性验证
	$keyb = md5(substr($key, 16, 16));
	// 密匙c用于变化生成的密文
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	// 参与运算的密匙
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	// 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，解密时会通过这个密匙验证数据完整性
	// 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();
	// 产生密匙簿
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	// 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	// 核心加解密部分
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		// 从密匙簿得出密匙进行异或，再转成字符
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		// substr($result, 0, 10) == 0 验证数据有效性
		// substr($result, 0, 10) - time() > 0 验证数据有效性
		// substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16) 验证数据完整性
		// 验证数据有效性，请看未加密明文的格式
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		// 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
		// 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
		$str = $keyc.str_replace('=', '', base64_encode($result));

		//转换下防止url传输出错
		$str = str_replace(array('+','/','='),array('-','_',''),$str);

		return $str;
	}
}












$path="";
$dir_path = "/www/upload";
if($remote_config['image_remote_storage']==1 and !empty($remote_config['space_name']) and !empty($remote_config['ftp_password']) and !empty($remote_config['ftp_name']))
{
	if(!empty($remote_config['remote_directory']))
	{
		$path='/'.$remote_config['remote_directory']."/";
	}
}
else
{
	$path=$dir_path."/"; 
}
$m=$_GET['m']?$_GET['m']:"";
if(!empty($m))
{	
	$path.=$m.'/';	
	if($m=='member' or $m=='shop' or $m=='product' or $m=='product/property' or $m=='album')
	{
		$b2bbuilder_auth=bgetcookie("USERID");
		$buid=$b2bbuilder_auth['0'];
		if($buid)
			$path.=$buid.'/';	
	}
	}
else
{
	$path.='all/';
}
$ist=$image_config['image_storage_type']?$image_config['image_storage_type']:"1";
switch ($ist){
	case "1":
	{	
		$path.=date('Y').'/'.date('m').'/'.date('d').'/';
		break;
	}
	case "2":
	{	
		$path.=date('Y').'/'.date('m').'/';
		break;
	}
	case "3":
	{	
		$path.=date('Y').'/';
		break;
	}
	default:
	{
		break;
	}
}
// $size=array('160','450');
//==============================================
session_start();
if($_SESSION['USER_LANG'])
	$config['language']=$_SESSION['USER_LANG'];
if(is_uploaded_file($_FILES['pic']['tmp_name']))
{
    $pic_type = "";
    switch ($_FILES['pic']['type'])
    {
        case "image/jpeg":
            $pic_type = ".jpg";break;
        case "image/png":
            $pic_type = ".png";break;
        case "image/gif":
            $pic_type = ".gif";break;
        default:
            $pic_type = ".mp3";
    }
	if($remote_config['image_remote_storage']==1 and !empty($remote_config['space_name']) and !empty($remote_config['ftp_password']) and !empty($remote_config['ftp_name']))
	{
		
		require_once('lib/php-sdk-master/upyun.class.php');
		
		$upyun = new UpYun("$remote_config[space_name]","$remote_config[ftp_name]","$remote_config[ftp_password]");
		try
		{
			$fh = fopen($_FILES['pic']['tmp_name'], 'rb');
			$pn=time().$pic_type;
			$rsp = $upyun->writeFile($path.$pn, $fh, True);   // 上传图片，自动创建目录
			fclose($fh);
			if($_GET['m']=='product')
			{	
				$fh = fopen($_FILES['pic']['tmp_name'], 'rb');
// 				foreach($size as $key=>$val)
// 				{
// 					$opts.$key = array(
// 						UpYun::X_GMKERL_TYPE    => 'square', // 缩略图类型
// 						UpYun::X_GMKERL_VALUE   => $val, // 缩略图大小
// 						UpYun::X_GMKERL_QUALITY => 100, // 缩略图压缩质量
// 						UpYun::X_GMKERL_UNSHARP => True // 是否进行锐化处理
// 					);
// 					$rsp = $upyun->writeFile($path.$pn."_".$val."X".$val.$pic_type, $fh, True, $opts.$key);   // 上传图片，自动创建目录
// 				}
				fclose($fh);
				$pn=$remote_config['remote_access_url'].$path.$pn;
				echo "<script>window.parent.load_pic('".$pn."');</script>";
			}
			else
			{
				$pn=$remote_config['remote_access_url'].$path.$pn;
				$str="window.parent.document.getElementById('$_GET[obj]').value='$pn';";
				if($_GET['m']=='material'){
				    $str.="window.parent.load_pic();";
				}
				$str.="if(window.parent.document.getElementById('$_GET[obj]_img')){window.parent.document.getElementById('$_GET[obj]_img').src='$pn';}";
				echo "<script>$str;window.parent.close_win();parent.$.jBox.close();</script>";
			}
		}
		catch(Exception $e) {
			echo $e->getCode();
			echo $e->getMessage();
		}
	}
	else
	{
		
		if(!empty($_GET['watermark']))
			$watermark=false;
		else
			$watermark=true;
			
		$pn=time().$pic_type;
		$pw=$_POST['pw'];
		$ph=$_POST['ph'];
		
		if(!file_exists($path))
		{
			mkdirs($path);
		}
		
		if($_GET['m']=='product')
		{
// 			foreach($size as $key=>$val)
// 			{
// 				makethumb($_FILES['pic']['tmp_name'], $path.$pn."_".$val."X".$val.$pic_type,$val,$val,false);
// 			}
			//750 500
			makethumb($_FILES['pic']['tmp_name'], $path.$pn,$pw,$ph,true,$wmark_config);
			$str="window.parent.load_pic();";
		}
		else
		{
			makethumb($_FILES['pic']['tmp_name'],$path.$pn,$pw,$ph,$watermark);
			if($_GET['m']=='material'){
			    $str="window.parent.load_pic();";
			}
		}
		
		
		if (!$image_direction=$image_config['image_direction']){
			$image_direction=$config['weburl'];
		}
		
		
		$pn=str_replace($dir_path, "", $path).$pn;
		
		if ($image_config['image_encode']){
			$pn=uploadEncode($pn,'ENCODE','!Ha@io#o2$01%4');
		}
		
		$pn=$image_direction.DIRECTORY_SEPARATOR.$pn;
		
		
		$str.="window.parent.document.getElementById('$_GET[obj]').value='$pn';";
		$str.="if(window.parent.document.getElementById('$_GET[obj]_img')){window.parent.document.getElementById('$_GET[obj]_img').src='$pn';}";
		echo "<script>$str;window.parent.close_win();</script>";
	}
	die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>图片上传</title>
</head>
<style>
*{font-family:Arial, Helvetica, sans-serif;}
td{font-size:12px; padding:3px;}
#preview{width:380px; height:260px; overflow:scroll; text-align:center;}
#preview img{border:1px solid #CCCCCC}
#pic{max-width:235px;}
</style>
<body>
<?php if(empty($_GET['pv'])){ ?>
<form action="" method="post" enctype="multipart/form-data">
<?php if($config['language']=='cn'){?>
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr align="center">
    <td><input name="pic" type="file" id="pic" /><br /><font style="color:#666666">(支持格式:Jpeg,Jpg Gif,Png 小于1MB)</font></td>
  </tr>
  <?php if(empty($_GET['re_pic'])){ ?>
  <tr align="center">
    <td>
	  宽度<input name="pw" type="text" id="pw" value="<?php if($_GET['pw']) echo $_GET['pw']; else echo 0;?>" size="3" />px 
	  高度<input name="ph" type="text" id="ph" value="<?php if($_GET['ph']) echo $_GET['ph']; else echo 0;?>" size="3" />px
	  </td>
  </tr>
  <?php } ?>
  <tr align="center">
    <td>
      <input type="submit" name="Submit" value="提交" />
      <input type="reset" onclick="window.parent.close_win();parent.$.jBox.close();" name="Submit2" value="取消" />
    </td>
  </tr>
</table>
<?php } else{ ?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td><input name="pic" type="file" id="pic"/><br /><font style="color:#666666">(Supported formats: Jpeg, Jpg, Gif, or Png Size: Max 1MB)</font></td>
  </tr>
  <?php if(empty($_GET['re_pic'])){ ?>
  <tr>
    <td>
	  Width<input name="pw" type="text" id="pw" value="<?php echo $_GET['pw'];?>" size="3" />px 
	  Height<input name="ph" type="text" id="ph" value="<?php echo $_GET['ph'];?>" size="3" />px
	  </td>
  </tr>
  <?php } ?>
  <tr>
    <td>
      <input type="submit" name="Submit" value="Submit" />
      <input type="reset" onclick="window.parent.close_win();" name="Submit2" value="Cancel" />
    </td>
  </tr>
</table>
<?php } ?>
</form>
<?php
}
else
{
?>
<div id="preview"></div>
<script>
str=window.parent.document.getElementById('<?php echo $_GET['obj'];?>').value;
if(str=='')
	str='图片地址为空，无法预览';
else
	str='<img src='+str+'>';
document.getElementById('preview').innerHTML=str;
</script>
<?php } ?>
</body>
</html>
